import Mock from "mockjs";
import { param2Obj } from "../utils/mUtils";
// 造数据
let List = [];
for (var i = 0; i < 200; i++) {
  List.push({
    id: Mock.mock("@increment()"),
    // id:'1',
    name: Mock.mock("@cname"),
    phone: Mock.mock({
      regexp: /^\ 1(3[0-9]|5[0-9]|7[0-9]|8[0-9])\d{8}$/,
    }).regexp,
    pay: "￥" + Mock.mock("@natural(1000, 5000)"),
    num: Mock.mock("@natural(10, 100)"),
    vip: Mock.mock("@natural(1, 10)"),
    lastTime: Mock.mock("@date"),
  });
}

// Mock.mock(接口名，请求类型，返回值)
Mock.mock(/\/getStudentData/, "get", (config) => {
  console.log("config get", param2Obj(config.url));
  let { input, page, pageSize, startTime, endTime } = param2Obj(config.url);
  let st = Date.parse(startTime);
  let et = Date.parse(endTime);
  let time = "";
  console.log("开始时间", st, "结束时间", et);
  let newList = List.filter((item) => {
    return item.name.indexOf(input) != -1 || item.phone.indexOf(input) != -1;
  });
  if (!isNaN(st) && !isNaN(et)) {
    let dateList = newList.filter((item, index) => {
      time = Date.parse(item.lastTime);
      return st <= time && time <= et;
    });
    let resultList = dateList.filter((item, index) => {
      return (page - 1) * pageSize <= index && index < page * pageSize;
    });
    return {
      code: 200,
      msg: "请求成功",
      // data: newList, //返回造的数据
      data: resultList, //返回搜索完后的数据
      total: dateList.length, //上传后台数据的个数
    };
  }
  // 分页逻辑  (page - 1) * pageSize <= index  < page *pageSize
  let newList2 = newList.filter((item, index) => {
    return (page - 1) * pageSize <= index && index < page * pageSize;
  });
  return {
    code: 200,
    msg: "请求成功",
    // data: newList, //返回造的数据
    data: newList2, //返回搜索完后的数据
    total: List.length, //上传后台数据的个数
  };
});

// 删除单个
Mock.mock(/\/deleteIdData/, "post", (config) => {
  console.log("config", config);
  let { id } = JSON.parse(config.body);
  let newList = List.filter((item) => {
    return item.id != id;
  });
  List = newList;
  return {
    code: 200,
    msg: "删除成功",
    data: null,
  };
});

// 批量删除
Mock.mock(/\/batchDelete/, "post", (config) => {
  let { ids } = JSON.parse(config.body);
  let newList = List.filter((item) => {
    return ids.indexOf(item.id) === -1;
  });
  List = newList;
  return {
    code: 200,
    msg: "批量删除成功",
    data: null,
  };
});

// 编辑
Mock.mock(/\/editData/, "post", (config) => {
  console.log(config.body);
  let { id, name, phone, pay, num, vip, lastTime } = JSON.parse(config.body);
  List.forEach((item) => {
    if (item.id == id) {
      item.name = name;
      item.phone = phone;
      item.pay = pay;
      item.num = num;
      item.vip = vip;
      item.lastTime = lastTime;
    }
  });
  return {
    code: 200,
    msg: "编辑成功",
    data: null,
  };
});
